package com.HeadlineSystem.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.HeadlineSystem.dao.NewsMapper;
import com.HeadlineSystem.pojo.News;
import com.HeadlineSystem.service.NewsService;
import com.HeadlineSystem.util.SessionUtil;

public class NewsServiceImpl implements NewsService {
	SqlSession session;
	NewsMapper newsMapper;
	SessionUtil su = new SessionUtil();

	public NewsServiceImpl() {
		session = su.getSession();
		newsMapper = session.getMapper(NewsMapper.class);
	}

	@Override
	public List<Map<String, Object>> findPageAll(Integer indexPage, Integer pageSize) {

		List<Map<String, Object>> list = newsMapper.findPageAll((indexPage - 1) * pageSize, pageSize);
		// su.close(session);
		return list;
	}

	/**
	 * @author THINK
	 * @return List<Map<String,Object>>
	 * @time 2017-7-19 15:18:56
	 * @desc 查询24小时热新闻
	 */
	public List<Map<String, Object>> findHour24() {

		List<Map<String, Object>> hourList = newsMapper.findHourTwentyTour();

		// 帅双
		hourList = this.getHour24(hourList);

		// su.close(session);
		return hourList;
	}

	private List<Map<String, Object>> getHour24(List<Map<String, Object>> list) {
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			Date createTime = (Date) map.get("create_time");// ��������ŷ�����ʱ��

			if (!checkNewsCreateTime(createTime)) {
				list.remove(i);// ����ʱ�䳬��24Сʱ���Ƴ�
			}
		}
		return list;
	}

	@Deprecated
	public boolean checkNewsCreateTime(Date createTime) {
		Date sysdate = new Date();// ��õ�ǰϵͳʱ��
		int sysDay = sysdate.getDay();
		int createDay = createTime.getDate();
		return sysDay - createDay > 1 ? false : true;
	}

	/**
	 * @author administrator
	 * @return boolean
	 * @time 2017年7月22日08:59:50
	 * @desc 发表文章
	 */
	public boolean addNewsInfo(News news) {
		news.setTilteImg(this.analysisImgSrc(news.getTilteImg()));
		int result = newsMapper.insertSelective(news);

		// .close(session);
		if (result > 0) {
			return true;
		}
		return false;
	}

	public String analysisImgSrc(String html) {
		Document doc = Jsoup.parse(html);
		Elements imagesSrc = doc.select("img");
		for (Element src : imagesSrc) {
			return src.attr("src");
		}
		return html;
	}

	/**
	 * 
	 * @author administrator
	 * @return news 
	 * @time 2017年7月22日09:06:26
	 * @desc 通过新闻ID查询新闻详情
	 */
	public Map<String, Object> findById(String id) {
		// TODO Auto-generated method stub
		return newsMapper.findNewsId(id);
	}
}
